package com.googlecode.sparda.commons.collection;

import java.util.Collection;
import java.util.Iterator;

public class SelectWork<C extends Collection<E>, E> {

	private final C collection;
	
	private final Predicate<? super E> predicate;
	
	public SelectWork(C collection, Predicate<? super E> predicate) {
		this.collection = collection;
		this.predicate = predicate;
	}
	
	public C resultIntoSameCollection() {
		final Iterator<E> iterator = this.collection.iterator();
		while(iterator.hasNext()) {
			final E element = iterator.next();
			if(this.predicate.notAccept(element))
				iterator.remove();
		}
		return this.collection;
	}
	
	public void resultInto(final Collection<E> result) {
		if(this.collection == result)
			throw new IllegalArgumentException("Cannot use same collection, use resultIntoSameCollection method or ConcurrentSelect.");
		for (E element : this.collection)
			if(this.predicate.accept(element))
				result.add(element);
	}
}
